package com.yanjue.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanjue.common.entity.User;
import com.yanjue.common.util.CommonUtil;
import com.yanjue.common.util.JwtUtil;
import com.yanjue.common.util.ResultUtil;
import com.yanjue.common.vo.account.UserVO;
import com.yanjue.mapper.UserMapper;
import com.yanjue.bo.UserBO;
import com.yanjue.common.util.Result;
import com.yanjue.common.vo.account.AuthVO;
import com.yanjue.service.UserService;
import com.yanjue.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

import static com.alibaba.nacos.client.utils.EnvUtil.LOGGER;
import static com.yanjue.common.constant.JwtConstant.EXPIRE_DAY;

/**
* @author yanju
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-01-16 12:33:44
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;




    /**
     * 用户登录
     *
     * @param loginName
     * @param password
     * @return
     */
    @Override
    public Result login(String loginName, String password) {
        log.info("开始登录在login函数里=============================");
        log.info("loginName = {},password = {}=====================",loginName,password);
        try{
            //1.查询数据库
            User user = this.userMapper.selectByLoginName(loginName);
            if (null == user) {
                log.info("登录失败，user为null=================");
                return ResultUtil.notFound().buildMessage("登录失败，用户不存在！");
            }

            //2.校验用户密码
            String encryptPwd = UserUtil.getUserEncryptPassword(loginName, password);
            log.info("校验密码，encryptPwd:{}======================",encryptPwd);
            if (!user.getUserPwd().equals(encryptPwd)) {
                return ResultUtil.verificationFailed().buildMessage("登录失败，密码输入错误！");
            }

            // 登录成功，返回用户信息
            AuthVO vo = new AuthVO();
            UserVO userVo = new UserVO();
            BeanUtils.copyProperties(user, userVo);
            String token = JwtUtil.buildJwt(this.getLoginExpre(), userVo);
            vo.setToken(token);

            log.info("vo登录设置token的vo:{}===========================",vo);
            vo.setUser(userVo);
            log.info("vo登录设置user的vo:{}=============================",vo);

            return ResultUtil.success(vo);
        } catch (Exception ex) {
            LOGGER.error("登录失败了！{}; loginName:{}", ex, loginName);
            return ResultUtil.fail().buildMessage("登录失败，服务器被吃了＝(#>д<)ﾉ ！请重试。 ");
        }
    }

    /**
     * 用户注册
     * @param userBO
     * @return
     */
    @Override
    public Result register(UserBO userBO) {
        //1.查询数据库是否有此人
        User dbUser = this.userMapper.selectByLoginName(userBO.getLoginName());
        if (dbUser != null) {
            //1.1.用户名存在，需要换
            return ResultUtil.verificationFailed().buildMessage(userBO.getLoginName() + "已存在，请使用其它登录名进行注册！");
        }

        User user = new User();
        BeanUtils.copyProperties(userBO, user);
        //密码加密
        //UserUtil.getUserEncryptPassword(user.getLoginName(),user.getUserPwd());
        String encryptPwd = UserUtil.getUserEncryptPassword(userBO.getLoginName(), userBO.getUserPwd());
        user.setUserPwd(encryptPwd);
        try{
            // 设置默认头像
            user.setHeadImgUrl("https://tu.sioe.cn/gj/qiege/image.jpg");
            user.setUuid(CommonUtil.getUUID());
            log.info("注册插入user表之前===========================");
            this.userMapper.insert(user);
            log.info("注册插入user表成功===========================");

        } catch (Exception ex) {
            LOGGER.error("注册用户失败了！{}; user:{}", ex, user);
            return ResultUtil.fail().buildMessage("注册失败，服务器被吃了! ＝(#>д<)ﾉ");
        }
        log.info("注册插入user表，，返回之前===========================");
        return ResultUtil.success().buildMessage("注册成功！请登录吧");
    }

    /**
     * 获取登陆过期时间
     * @return
     */
    private Date getLoginExpre(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, EXPIRE_DAY);
        return calendar.getTime();
    }
}




